package main

import (
	"fmt"
	"net"
	"strings"
)

type User struct {
	Name   string
	Addr   string
	C      chan string
	conn   net.Conn
	server *Server
}

// NewUser 创建一个新的用户
func NewUser(conn net.Conn, server *Server) *User {
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name:   userAddr,
		Addr:   userAddr,
		C:      make(chan string),
		conn:   conn,
		server: server,
	}
	// 开始监听用户的管道信息
	go user.ListenMessage()
	return user
}

// ListenMessage 监听管道信息
func (this *User) ListenMessage() {
	for {
		msg := <-this.C
		_, err := this.conn.Write([]byte(msg + "\r\n"))
		if err != nil {
			return
		}
	}
}

// Online 用户上线业务
func (this *User) Online() {
	// 用户上线，将用户加入到onlineMap中
	this.server.mapLock.Lock()
	this.server.OnlineMap[this.Name] = this
	this.server.mapLock.Unlock()
	// 广播用户上线消息
	this.server.BroadCast(this, "online")
}

// Offline 用户下线业务
func (this *User) Offline() {
	// 用户下线，将用户从onlineMap中删除
	this.server.mapLock.Lock()
	delete(this.server.OnlineMap, this.Name)
	this.server.mapLock.Unlock()
	// 广播用户下线消息
	this.server.BroadCast(this, "offline")
}

// DoMessage 用户发送广播消息
func (this *User) DoMessage(msg string) {
	if msg == "who" {
		// 查询当前在线用户
		this.server.mapLock.Lock()
		for _, cli := range this.server.OnlineMap {
			onlineMsg := "[" + cli.Addr + "]" + cli.Name + ": " + "online\r\n"
			this.SendMsg(onlineMsg)
		}
		this.server.mapLock.Unlock()
	} else if len(msg) > 7 && msg[:7] == "rename|" {
		// 消息格式 rename|张三
		newName := strings.Split(msg, "|")[1]
		// 判断用户名是否已经存在
		_, ok := this.server.OnlineMap[newName]
		if ok {
			this.SendMsg("username is already exist, please change another name\r\n")
		} else {
			this.server.mapLock.Lock()
			delete(this.server.OnlineMap, this.Name)
			this.server.OnlineMap[newName] = this
			this.server.mapLock.Unlock()
			this.Name = newName
			this.SendMsg("success change your name :" + this.Name + "\r\n")
		}
	} else if len(msg) > 4 && msg[:3] == "to|" {
		// 消息格式 to|张三|消息内容
		// 查找用户
		remoteName := strings.Split(msg, "|")[1]
		if remoteName == "" {
			this.SendMsg("message format error, please input : to|username|message\r\n")
			return
		}
		// 获取用户
		remoteUser, ok := this.server.OnlineMap[remoteName]
		if !ok {
			this.SendMsg("user does not exist\r\n")
			return
		}
		// 获取消息内容
		content := strings.Split(msg, "|")[2]
		if content == "" {
			this.SendMsg("message content is empty\r\n")
		}
		remoteUser.SendMsg(this.Name + " say to you: " + content + "\r\n")
		this.SendMsg("you say to " + remoteUser.Name + " : " + content + "\r\n")
	} else {
		this.server.BroadCast(this, msg)
	}
}

// SendMsg 给当前用户发消息
func (this *User) SendMsg(msg string) {
	_, err := this.conn.Write([]byte(msg))
	if err != nil {
		fmt.Println("SendMsg error :", err)
		return
	}
}
